package com.newly.center.sys.service.loginRecord.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newly.center.sys.service.loginRecord.api.ILoginRecordService;
import com.newly.center.sys.service.tenant.api.ITenantService;
import com.newly.common.base.constants.AuthConstant;
import com.newly.common.base.constants.CommonConstant;
import com.newly.common.base.entity.PageUtils;
import com.newly.common.base.entity.auth.ICurrentTenant;
import com.newly.common.base.entity.sys.loginRecord.dto.LoginRecordDto;
import com.newly.common.base.entity.sys.loginRecord.po.LoginRecordPo;
import com.newly.common.base.entity.sys.tenant.po.TenantPo;
import com.newly.common.core.utils.ConverseUtils;
import com.newly.common.core.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: newly-parent
 * @description: 登录历史
 * @author: guan
 * @create: 2022-02-18 10:06
 */
@Service
@Slf4j
public class LoginRecordService extends AbstractLoginRecordService implements ILoginRecordService {

    @Override
    public boolean save(LoginRecordDto loginRecordDto) {
        LoginRecordPo loginRecordPo = BeanUtil.copyProperties(loginRecordDto, LoginRecordPo.class);

        DateTime currentDateTime = DateUtil.date();
        loginRecordPo.setBeginTime(currentDateTime);
        loginRecordPo.setCreateTime(currentDateTime);
        loginRecordPo.setUpdateTime(currentDateTime);

        loginRecordPo.setUsername(loginRecordDto.getUsername());
        loginRecordPo.setStatus(loginRecordDto.getStatus());
        loginRecordPo.setDel(CommonConstant.DeleteFlag.NO_DELETE.getCode());

        loginRecordPo.setOperSystem(requestUtils.getOperationSystem());
        loginRecordPo.setIp(requestUtils.getIp());
        loginRecordPo.setBrowser(requestUtils.getBrowse());

        int insert = loginRecordMapper.insert(loginRecordPo);
        return insert > 0;
    }

    @Override
    public PageUtils list(Integer offset, Integer limit, String fromTime, String toTime, String keyword) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();

        LambdaQueryWrapper<LoginRecordPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(LoginRecordPo::getCreateTime);

        if (!currentTenant.isDev()) {
            List<String> usernames = this.getUsernames(currentTenant);
            if (ObjectUtil.isEmpty(usernames)) return null;
            wrapper.eq(LoginRecordPo::getUsername, usernames);
        }

        IPage<LoginRecordPo> iPage = new Page<>(offset, limit);

        // 登录开始时间
        if (StrUtil.isNotBlank(fromTime) && StrUtil.isNotBlank(toTime)) {
            wrapper.between(LoginRecordPo::getBeginTime, fromTime, toTime);
        }

        // 关键字
        if (StrUtil.isNotBlank(keyword)) {
            wrapper.like(LoginRecordPo::getUsername, keyword)
                    .or().like(LoginRecordPo::getBrowser, keyword)
                    .or().like(LoginRecordPo::getOperSystem, keyword)
                    .or().like(LoginRecordPo::getIp, keyword)
                    .or().like(LoginRecordPo::getRemark, keyword);
        }

        iPage = loginRecordMapper.selectPage(iPage, wrapper);
        return new PageUtils(iPage);
    }

    @Override
    public LoginRecordPo getById(Long loginRecordId) {
        List<LoginRecordPo> loginRecordPos = getByIds(Arrays.asList(loginRecordId));
        if (ObjectUtil.isNotEmpty(loginRecordPos)) {
            return loginRecordPos.get(0);
        }
        return null;
    }

    @Override
    public List<LoginRecordPo> getByIds(List<Long> loginRecordIds) {
        if (ObjectUtil.isEmpty(loginRecordIds)) return null;
        return loginRecordMapper.selectBatchIds(loginRecordIds);
    }

    @Override
    public boolean removeByIds(List<Long> loginRecordIds) {
        if (ObjectUtil.isEmpty(loginRecordIds)) return false;
        int delete = loginRecordMapper.deleteBatchIds(loginRecordIds);
        return delete > 0;
    }

    @Override
    public boolean clear() {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        LambdaQueryWrapper<LoginRecordPo> wrapper = new LambdaQueryWrapper<>();
        if (!currentTenant.isDev()) {
            List<String> usernames = this.getUsernames(currentTenant);
            if (ObjectUtil.isEmpty(usernames)) return false;
            wrapper.eq(LoginRecordPo::getUsername, usernames);
        }
        int delete = loginRecordMapper.delete(wrapper);
        return delete > 0;
    }

    @Override
    public boolean modifyEndTime() {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        // 拿到当前用户最近一次登录记录
        LambdaQueryWrapper<LoginRecordPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(LoginRecordPo::getCreateTime);
        wrapper.eq(LoginRecordPo::getUsername, currentTenant.getUsername());
        List<LoginRecordPo> loginRecordPos = loginRecordMapper.selectList(wrapper);
        if (ObjectUtil.isEmpty(loginRecordPos)) return false;

        LoginRecordPo lastRecordPo = loginRecordPos.get(0);
        DateTime currentDateTime = DateUtil.date();
        lastRecordPo.setUpdateTime(currentDateTime);
        lastRecordPo.setEndTime(currentDateTime);
        int update = loginRecordMapper.updateById(lastRecordPo);
        return update > 0;
    }
}
